﻿var test = false;

var isScrolling=false;
var scrollQueue=0;
var hasChannelLoaded=false;
var amountScrolled;

var isRepeat = false;
var atSpecTime = false;

var displayCount = 0;//for the listing on the div
var taskBarHeight = 16;
var taskTypeSelected = "reminder";
var scheduleTypeSelected= "repeat";
var taskList = new Array();
var elementsList = new Array();
var taskIds = new Array();


function view_onOpen()
{
  setInterval("Timer();", 1000);
}




function ShowTaskbar() {
   //debug.trace("ShowTaskbar:"+taskList.length);
   var latestTask = taskList[taskList.length-1];
   var title = latestTask.title;
   var id = latestTask.id;
   displayCount ++;
   var tooltip = "Title: "+latestTask.title +"\nTime: " + latestTask.timeCreated.toString() +"\nMessage: " + latestTask.msg ;
   if(latestTask.atSpecTime){
     tooltip += "\nSchld Time: " + latestTask.schTime.toString();
   }else{
     tooltip += "\nInterval: " + latestTask.interval;
     if(latestTask.isRepeat)
      tooltip += " (repeats)"
   }
   
   //cursor="hand" onclick="OnTaskbar('+(taskIds.length-1)+')"
   var theElement = div_list.appendElement('<div x="5" height="'+(taskBarHeight-1)+'" name="task_bk" width="159">'
                                         +'<img height="'+(taskBarHeight-1)+'" width="159" x="0" y="0" src="images/task_bk.gif"/>'
                                         +'<img x="2" y="0" height="15" width="13" src="images/icon_task.gif"/>'
                                         +'<label x= "15" y= "0" height="'+(taskBarHeight-1)+'" width="120" font="Terminal" enabled="true" tooltip="'+tooltip+'">'+title+'</label>'
                                         +'<button onclick="TrashOnclickHandler('+(taskIds.length-1)+','+true+')" height="13" width="12" x="135" y="1" downImage="images/icon_trash.gif" image="images/icon_trash.gif" overImage="images/icon_trash_o.gif"/></div>'); 
  
   theElement.y= (displayCount-1)*taskBarHeight;
   div_list.height = displayCount*taskBarHeight;
   elementsList[elementsList.length] = theElement;

   SetScrollBar();
}

function SetScrollBar() {
  if(div_list.height>140){
     btn_up.visible = true;
     btn_down.visible = true;

     div_list.y = 140-div_list.height;
  }else {
     btn_up.visible = false;
     btn_down.visible = false;
     div_list.y = 1;
  }
}

function OnTaskbar(taskIndex) {
   var subTaskId  = taskIds[taskIndex]; 
   debug.trace("subTaskID:" + subTaskId);
   var i = 0; 
   for(;i<taskList.length;i++)
   {
    if(taskList[i].id==subTaskId){
      break;
   }
  }
}

function TrashOnclickHandler(index,flag) {
   if(confirm("Are you sure want to delete the task"))
     SubtractTask(index,flag);
}


function SubtractTask(index,flag) {
  
  //debug.trace("Sub Task index:"+index +" -flag-00"+flag);
 
  var subTaskId  = taskIds[index]; 
  //debug.trace("subTaskID :"+ subTaskId);
  if(flag)//forcebly deleting the task
    clearInterval(subTaskId);
   
   
  //nullifying the task from the TaskList
  var i = 0; 
  //debug.trace("taskList.length  " + taskList.length);
  for(;i<taskList.length;i++)
  {
    if(taskList[i].id==subTaskId){
       taskList[i] = undefined;
       break;
    }
  }
  var elementIndx = i;
  //trim the taskList
  for(;i<taskList.length-1;i++)
    taskList[i] = taskList[i+1];
  taskList.length = taskList.length - 1;
  //debug.trace("ElementsListLenngth:" + elementsList.length);
  //debug.trace("elementIndx:" + elementIndx);
  //remove the taskElement from the elementsList and also from the div_list
  var subElement = elementsList[elementIndx]; 
  div_list.removeElement(subElement);
  
  for(i=elementIndx;i<elementsList.length-1;i++)
  {
    var tmpEle = elementsList[i+1];
    tmpEle.y = tmpEle.y - taskBarHeight;
    elementsList[i] = tmpEle;
  }
  elementsList.length = elementsList.length-1;
  displayCount --;
  div_list.height = displayCount*taskBarHeight;

  SetScrollBar();
}

//'Add Task' panel functions and handlers
function ShowAddTaskPanel() {
   div_addtask.visible = true;
   div_addtask.x = -175;
   //beginAnimation("div_addtask.x += 45; if(div_addtask.x>=17){ div_addtask.x=17;}",0,10,70);
   div_addtask.x=17;

   btn_exe.enabled = false;
   txt_im.enabled = false; 
   btn_add.enabled = false;
   btn_help.enabled = false;
   //clear fields
   txt_msg.value = "";
   txt_im.value = "";
   txt_title.value = "";
   txt_interval.value = "";
   lbl_filepath.innerText = "";
   txt_hour.value="";
   txt_min.value="";
   txt_sec.value="";
  
}
//OK Button's onclick event handler
function DefineTask() {
    //validations
    var msg="";

    var dtime = new Date();

    if(txt_title.value=='')
      msg += "Title should not be null\n";
    if(taskTypeSelected=='reminder' || taskTypeSelected=='im') {
      if(taskTypeSelected=='im' && txt_im.value=='')
         msg += "Enter valid Gtalk ids(comma seperated)\n";
      if(txt_msg.value=='')
        msg += "Message should not be null\n";
    }else if(taskTypeSelected=='exe'){
       if(lbl_filepath.innerText=='')
         msg += "Select an executable file by clicking the button\n";
    }
    var intrl = txt_interval.value;
    if(!atSpecTime){    
      if(intrl == '' || !isValidNumber(intrl)) {
         msg += "Interval should not be null\n";
      }else {
        intrl = parseInt(intrl);
      }
    }else {
      var t_h = txt_hour.value;
      var t_m = txt_min.value;
      var t_s = txt_sec.value;
      if(t_h.match(/\d{1,2}/) && t_m.match(/\d{1,2}/) && t_s.match(/\d{1,2}/))
      {
        try{
         hours = parseInt(t_h);
         mins = parseInt(t_m);
         secs = parseInt(t_s);
         dtime.setHours(hours);
         dtime.setMinutes(mins);
         dtime.setSeconds(secs);
         debug.trace(dtime.getTime() - new Date().getTime());
         if(dtime.getTime() < new Date().getTime()) {
            msg += 'Time entered is less than current time\n';
         }//if date_entered..
        }catch(Exp){ debug.trace(Exp.message);
           msg += 'Time entered is wrong exp\n';
        }
      }else{ 
         msg += 'Time entered is wrong\n';
      }
      intrl = dtime.getTime() - new Date().getTime();
      intrl = intrl/1000;
      //if(intrl<=0)
      //   msg += "Some Thing is Wrong\n";
    }//else

   if(msg!=''){
    var strMsg = new String(msg);
    
    alert(msg);
   }
   else {
      var newTask =new Task();
      newTask.title = txt_title.value;
      newTask.taskType = taskTypeSelected;
      newTask.msg = txt_msg.value;
      newTask.sendto = txt_im.value;
      newTask.interval = intrl;
      newTask.isRepeat = isRepeat;
      newTask.timeCreated = new Date(); 
      newTask.schTime = dtime;
      newTask.atSpecTime = atSpecTime;
      newTask.exePath = lbl_filepath.innerText;
      var taskToken = "";


     
      //Schedule the defined Task
      var script ='alert("wow!")';
      if(newTask.taskType=='reminder'){
         script = 'ShowReminder("'+newTask.msg + '");';
      }else if(newTask.taskType=='exe') {
         script = 'ShellExe("'+ newTask.exePath +'");';
      }else {
         script = 'SendIm("'+newTask.msg+'","'+newTask.sendto+'","'+newTask.title+'");';
      }
      //
      

      if(newTask.isRepeat) 
        taskToken = setInterval(script, intrl*1000);
      else{
         //Additionally the removing the task from list
         //script = script+ 'SubtractTask('+taskCount+')';
         script = script+ 'SubtractTask('+taskIds.length+')';
         taskToken = setTimeout(script, intrl*1000);
      }
      newTask.id = taskToken;
      taskIds[taskIds.length] = taskToken;
   

      //Add to Tasks Array
      //taskList[taskCount++] = newTask;
      taskList[taskList.length] = newTask;

      DismissAddTaskPanel();
      ShowTaskbar();
   }
}//Onclick 'OK' DefineTask

function ShowReminder(message) {
  alert("Reminder from Desktop Cron\n------------------------------------\n"+message);

}

function ShellExe(filePath) {
   var run = new ActiveXObject("Shell.Application"); 
   run.ShellExecute(filePath); 
}

function SendIm(message,sendto,title) {
  var send = sendto.split("[,;]");
  var msg = "\n*" + message +"*";
  for(i=0;i<send.length;i++) { debug.trace(send[i]);
     googleTalk.SendTalkText(send[i],msg);
  }
}


function DismissAddTaskPanel() {
   //beginAnimation("div_addtask.x -= 25; if(div_addtask.x<=-175){ div_addtask.x=-175;}",0,100,200);
   div_addtask.x=-175;
   btn_add.enabled = true;
   div_addtask.visible = true;

   btn_help.enabled = true;
}


//utility functions
function isValidNumber(val) {
  var re  = /^[1-9]+\d*/;
  return val.match(re);
}

//Add panel handlers
function TaskTypeCheckBoxHandler(type) {
  taskTypeSelected = type;
  if(type=='exe') {
     chk_exe.value = true; chk_exe.image="images\\option\\chk_chk_normal.png"; chk_exe.checkedOverImage = "images\\option\\chk_chk_over.png";
     chk_im.value=false; chk_im.image = "images\\option\\chk_normal.png"; chk_im.overImage = "images\\option\\chk_over.png";
     chk_reminder.value=false; chk_reminder.image = "images\\option\\chk_normal.png"; chk_reminder.overImage = "images\\option\\chk_over.png";
     //also
     txt_msg.value=''; 
     txt_msg.enabled=false; txt_im.enabled = false; btn_exe.enabled = true;
  }else if(type=='im') {
     chk_exe.value = false; chk_exe.image="images\\option\\chk_normal.png"; chk_exe.overImage="images\\option\\chk_over.png";
     chk_im.value=true; chk_im.image="images\\option\\chk_chk_normal.png"; chk_im.checkedOverImage = "images\\option\\chk_chk_over.png";
     chk_reminder.value=false; chk_reminder.image="images\\option\\chk_normal.png"; chk_reminder.overImage = "images\\option\\chk_over.png";
     //also
     txt_msg.enabled=true;  btn_exe.enabled = false; txt_im.enabled = true;
  }else if(type=='reminder') {
     chk_exe.value = false; chk_exe.image="images\\option\\chk_normal.png"; chk_exe.overImage="images\\option\\chk_over.png";
     chk_im.value=false; chk_im.image = "images\\option\\chk_normal.png"; chk_im.overImage = "images\\option\\chk_over.png";
     chk_reminder.value=true; chk_reminder.image="images\\option\\chk_chk_normal.png"; chk_reminder.checkedOverImage="images\\option\\chk_chk_over.png";
     //also
     txt_msg.enabled=true;  txt_im.enabled = false; btn_exe.enabled = false;
  }
}
function OnRepeat() {
  isRepeat = !isRepeat;
}
function OnAtSpecTime() {
  atSpecTime = !atSpecTime;
  chk_repeat.enabled = !atSpecTime;
 
   if(atSpecTime){
     chk_repeat.value = false; 
     isRepeat = false;
     chk_repeat.image = "stock_images\\chk_normal.png";

     lbl_interval.innerText = "Time";
     txt_interval.visible = false;
     txt_hour.visible = true;
     txt_min.visible = true;
     txt_sec.visible = true;
     lbl_mins.innerText = "H:m:s";
   }else{
     lbl_interval.innerText = "Interval";
     txt_interval.visible = true;
     txt_hour.visible = false;
     txt_min.visible = false;
     txt_sec.visible = false;
     lbl_mins.innerText = "mins";
     
   }
  
}
function ScheduleTypeCheckBoxHandler(type) {
 scheduleTypeSelected = type;
 if(type=="repeat") {
   chk_repeat.value = true; chk_repeat.image = "stock_images\\chk_chk_normal.png";
   chk_once.value = false; chk_once.image = "stock_images\\chk_normal.png";
 }else if(type=="once") {
   chk_once.value = true; chk_once.image = "stock_images\\chk_chk_normal.png";
   chk_repeat.value = false; chk_repeat.image = "stock_images\\chk_normal.png";
 }
}

function Exe_onclickHandler() {
   var filePath = BrowseForFile("Executable Files|*.exe;*.bat");
   var str = new String(filePath);
   str = str.replace(/\\/g,"/");
   filePath = str;
   //txt_msg.value = filePath;
   lbl_filepath.innerText = str;//str.substring(str.length-15,str.length);
   txt_msg.enabled = false;
}

function ScrollUp () {
  //debug.trace("ScrollUp:" + div_list.y);
  div_list.y = div_list.y + 5;
  if(div_list.y>1)
   div_list.y = 1;
}

function ScrollDown() {
  //debug.trace("ScrollDown:" + div_list.y);
  div_list.y = div_list.y - 5;
  if(div_list.y + div_list.height < 140)
   div_list.y = 140-div_list.height;
}


function reset() {
  if(confirm("Are you sure want to Reset??\n All the tasks will be lost.")){
    taskTypeSelected = "reminder";
    scheduleTypeSelected= "repeat";
    taskList = new Array();
    for(var i=0;i<elementsList.length;i++)
      div_list.removeElement(elementsList[i]);
  
    elementsList = new Array();
    taskIds = new Array()
    displayCount = 0;//for the listing on the div
  }
}


function Timer() {

  // show the time
  var date = new Date();
  var h = date.getHours();
  var m = date.getMinutes();
  var s = date.getSeconds();

  var time = (h<10?"0"+h:h) + ":" + (m<10?"0"+m:m) + ":" + (s<10?"0"+s:s);
  lbl_time.innerText = time;

}

function CloseHelp() {
  div_helptext.visible = false;
  btn_add.enabled =true;
}
function ShowHelp() {
  div_helptext.visible = true;
  btn_add.enabled =false;
}